﻿using System;
using System.Reflection;
using System.Data.SqlClient;

using Builderator.Core.Interfaces;

namespace Builderator.Core.Action
{
    public class ActionBase : Document, IDatabase, IAction, IDocument
    {
        public event DebugMessageDelegate DebugMessageEvent;

        [DocumentProperty("Identifier", typeof(Guid), true)]
        public Guid Identifier
        {
            get;
            set;
        }

        [DocumentProperty("Name", typeof(String), false)]
        public string Name
        {
            get;
            set;
        }

        [DocumentProperty("Type", typeof(Guid), true)]
        public Guid Type
        {
            get;
            set;
        }

        [DocumentProperty("Previous", typeof(Guid), true)]
        public Guid Previous
        {
            get;
            set;
        }

        [DocumentProperty("Next", typeof(Guid), true)]
        public Guid Next
        {
            get;
            set;
        }

        [DocumentProperty("Associated", typeof(Guid), true)]
        public Guid Associated
        {
            get;
            set;
        }

        public VariableDictionary Variables
        {
            get;
            set;
        }

        public ActionBase(string name, Guid type)
            : base()
        {
            this.Identifier = Guid.NewGuid();

            this.Name = name;

            this.Type = type;

            this.Previous = Guid.Empty;

            this.Next = Guid.Empty;

            this.Associated = Guid.Empty;
        }

        public ActionBase(Guid type)
            : this(string.Empty, type)
        {

        }

        public virtual string Select(DatabaseTable table)
        {
            return string.Format("SELECT * FROM actions WHERE identifier='{0}'", this.Identifier.ToString());
        }

        public virtual string Insert(DatabaseTable table)
        {
            return string.Format("INSERT INTO actions VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", this.Identifier, this.Name, this.Type, this.Previous, this.Next, this.Associated, this.Serialize());
        }

        public virtual string Update(DatabaseTable table)
        {
            return string.Format("UPDATE actions SET previous='{0}', next='{1}', associated='{2}', settings='{3}' WHERE identifier='{4}'", this.Previous.ToString(), this.Next.ToString(), this.Associated.ToString(), this.Serialize(), this.Identifier.ToString());
        }

        public virtual string Delete(DatabaseTable table)
        {
            return string.Format("DELETE FROM actions WHERE identifier='{0}'", this.Identifier.ToString());
        }

        public void DebugMessage(string message)
        {
            if (this.DebugMessageEvent != null)
                this.DebugMessageEvent(message);
        }
    }
}